<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Sale_Detail_Results_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('xlsimport/php-excel-reader/excel_reader2');
        $this->load->helper('xlsimport/spreadsheetreader.php');
        $this->load->model('saledetailresult', '', true);
        $this->load->model('user', '', true);

        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }

        $this->LoggedUser = $this->user->getLoggedUser();
        
        $this->load->library('authentication');$this->load->helper('t');
        $this->loggedUser = $this->authentication->getLoggedUser();$this->authentication->redirectIfNotBe( array('SS', 'KAS'));
    }

    function index_content($tlCode = 'all', $title = 'all') {
        $this->load->helper('form');
        $this->load->model('evaluation', '', true);

        // load dropdown region, title, thực hiện filter
        $this->load->model('region');
        $regions = $this->region->get_list();
        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;

        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;

        $teamleaders = $this->user->get_list_by_title(array('NRTL', 'BSTL', 'PGTL', 'MedTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
        $viewData['teamleaders'] = $teamleaders;

        $users = array();
        if ($title != 'all') {
            $viewData['filterTitle'] = $title;
            switch ($title) {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    break;
                case 'Medical': 
                    $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
                    
                    break;
            }
        } else {
            $users = $this->user->get_list_by_title(get_employee_titles(), array('status' => 'active', 'supervisor_code' => $this->loggedUser->code));
        }
        if ($tlCode != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['teamleader_code'] == $tlCode) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterTL'] = $tlCode;
        }
        
        // đợt đánh giá mới nhất
        $evaluation = $this->evaluation->get_last();
        $viewData['evaluation'] = $evaluation;
        
        // truy vấn kết quả của từng user
        $daCoSP= 0;
        $chuaCoSP = 0;
        foreach ($users as &$eachUser) {
            $saleResult = $this->saledetailresult->get_first_where(array('user_code' => $eachUser['code'], 'eid' => $evaluation['id']));
            $eachUser['saleResult'] = $saleResult;
            if($eachUser['code'] == 'f0090')
            {
                var_dump($eachUser);
            }
            if($saleResult == false)
            {
                $chuaCoSP++;
            }
            else
            {
                $daCoSP++;
            }
        }
        
        $viewData['rows'] = $users;
        $viewData['chuaCoSP'] = $chuaCoSP;
        $viewData['daCoSP'] = $daCoSP;
        
        $chartData = array();
        $chartData[] = array('Loại', 'Số lượng');
        $chartData[] = array('Đã có Sales performance', $daCoSP);
        $chartData[] = array('Chưa có Sales performance', $chuaCoSP);        
        $viewData['chartData'] = json_encode($chartData);
        
        return $viewData;
    }

    function index($ss_code = 'all', $title = 'all') {

        $viewData = $this->index_content($ss_code, $title);

        $this->load->view(get_folder($this->loggedUser->title).'/sale_detail_results_list', $viewData);
        
    }
    
    function report($ss_code = 'all', $title = 'all') {

        $viewData = $this->index_content($ss_code, $title);

        $this->load->view(get_folder($this->loggedUser->title).'/sale_detail_results_report', $viewData);
        
    }
    
    function upload() {
//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        if (isset($_FILES['xlsfile'])) {
            $targets = 'xls/';
            $targets = $targets . basename($_FILES['xlsfile']['name']);
            $docadd = ($_FILES['xlsfile']['name']);
            if (move_uploaded_file($_FILES['xlsfile']['tmp_name'], $targets)) {
                $Filepath = $targets;
                $allxlsdata = array();
                date_default_timezone_set('UTC');

                $StartMem = memory_get_usage();
                //echo '---------------------------------'.PHP_EOL;
                //echo 'Starting memory: '.$StartMem.PHP_EOL;
                //echo '---------------------------------'.PHP_EOL;

                try {
                    $Spreadsheet = new SpreadsheetReader($Filepath);
                    $BaseMem = memory_get_usage();

                    $Sheets = $Spreadsheet->Sheets();

                    //echo '---------------------------------'.PHP_EOL;
                    //echo 'Spreadsheets:'.PHP_EOL;
                    //print_r($Sheets);
                    //echo '---------------------------------'.PHP_EOL;
                    //echo '---------------------------------'.PHP_EOL;

                    foreach ($Sheets as $Index => $Name) {
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** Sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;

                        $Time = microtime(true);

                        $Spreadsheet->ChangeSheet($Index);

                        foreach ($Spreadsheet as $Key => $Row) {
                            //echo $Key.': ';
                            if ($Row) {
                                //print_r($Row);
                                $allxlsdata[] = $Row;
                            } else {
                                var_dump($Row);
                            }
                            $CurrentMem = memory_get_usage();

                            //echo 'Memory: '.($CurrentMem - $BaseMem).' current, '.$CurrentMem.' base'.PHP_EOL;
                            //echo '---------------------------------'.PHP_EOL;

                            if ($Key && ($Key % 500 == 0)) {
                                //echo '---------------------------------'.PHP_EOL;
                                //echo 'Time: '.(microtime(true) - $Time);
                                //echo '---------------------------------'.PHP_EOL;
                            }
                        }

                        //	echo PHP_EOL.'---------------------------------'.PHP_EOL;
                        //echo 'Time: '.(microtime(true) - $Time);
                        //echo PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** End of sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                    }
                } catch (Exception $E) {
                    echo $E->getMessage();
                }
                
                $this->load->model('evaluation', '', true);
                $evaluation = $this->evaluation->get_last();


                $this->saledetailresult->import($allxlsdata, $evaluation['id']);
            }
        } else {
            echo "Error: " . $_FILES["file"]["error"];
        }
        redirect(get_folder($this->loggedUser->title).'/sale_detail_results');
    }
    
    
    
    
    function add() {
        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
//        $this->load->model('category', '', TRUE);
//        $viewData['category'] = $this->category->category_dropdown();
        
//        $this->load->model('difficult_level', '', TRUE);
//        $viewData['difficult_level'] = $this->difficult_level->level_dropdown();
        
//        $viewData['title'] = "Add new question";
        
        $this->load->model('attituderesult');
        $viewData['attResults'] = $this->attituderesult->get_list('0');
        
        $viewData['users'] = $this->user->user_list('0');
        
        if ($this->input->post('Command') && $this->input->post('Command') == 'Add') {
            // Thực hiện form validation
            $newRow = array(
                'user_id' => $this->input->post('user_id'),
                'ar_id' => $this->input->post('ar_id')
            );
            
            $viewData['addResult'] = $this->saledetailresult->insert($newRow);
        }
        

        $this->load->view(get_folder($this->loggedUser->title).'/sale_detail_result_add', $viewData);
    }

    function edit($id) {

//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }


//        $this->load->model('category', '', TRUE);
//        $viewData['category'] = $this->category->category_dropdown();
//
//        $this->load->model('difficult_level', '', TRUE);
//        $viewData['difficult_level'] = $this->difficult_level->level_dropdown();

        if ($this->input->post('Command') && $this->input->post('Command') == 'Edit') {
            //print_r($_POST);
            
            $newSaleResult = array(
                'id' => $id,
                'name' => $this->input->post('name')
            );
            
            $viewData['editResult'] = $this->attitudeuserdetail->update($newSaleResult);
        }
        
        $viewData['attitudeResult'] = $this->attitudeuserdetail->get($id);

//        $viewData['title'] = "Edit question";

        $this->load->view(get_folder($this->loggedUser->title).'/attitude_user_detail_edit', $viewData);
    }

    function delete($id) {
//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        $viewData['deleteResult'] = $this->attitudeuserdetail->delete($id);

        redirect(get_folder($this->loggedUser->title).'/attitude_user_details', 'refresh');
    }
    
    
// get desired question for particular subject and difficulty level
    function get_level_question($difficulty_level, $category) {
        $this->db->where("cid", $category);
        $this->db->where("did", $difficulty_level);
        $query = $this->db->get("qbank");
        $num = $query->num_rows();
        echo $num;
    }

}
?>













